package com.fast.develop.configuration.resource;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import com.fast.develop.core.io.db.DbResource;
import com.fast.develop.core.io.db.DbResourceRepository;
import com.fast.develop.meta.base.resource.MultResource;
import com.fast.develop.meta.base.resource.PathResource;

import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

/**
 * @author 莫寅
 * @createTime 2022-06-25 00:22
 * @desc：
 */
public class MetaDbFileMultResource implements MultResource<PathResource> {

    private List<PathResource> resourceList;
    private DbResourceRepository<DbResource> dbResourceRepository;

    public MetaDbFileMultResource(DbResourceRepository dbResourceRepository){
        this.dbResourceRepository = dbResourceRepository;
        readResource();
    }

    private void readResource(){
        this.resourceList = dbResourceRepository.list().stream()
                .filter(dbResource -> FileUtil.getSuffix(dbResource.getPath()).equals("json"))
                .map(dbResourceEntity -> {
            return new PathResource(dbResourceEntity.getPath(), IoUtil.toUtf8Stream(dbResourceEntity.getContent()));
        }).collect(Collectors.toList());
    }

    @Override
    public Iterator<PathResource> iterator() {
        return Collections.unmodifiableList(this.resourceList).iterator();
    }

    @Override
    public Stream<PathResource> stream() {
        return StreamSupport.stream(spliterator(), false);
    }


    @Override
    public Spliterator<PathResource> spliterator() {
        return Spliterators.spliterator(getResources(), 0);
    }


    @Override
    public PathResource[] getResources(){
        return this.resourceList.toArray(new PathResource[0]);
    }

    @Override
    public List<InputStream> getInputStreams() {
        return this.resourceList.stream().map(PathResource::getInputStream).collect(Collectors.toList());
    }

    @Override
    public void reload() {
        readResource();
    }

}
